<?php

namespace app\index\controller;

use app\model\Boutcardorder;
use app\model\GoodsSkuValue;
use think\exception\ValidateException;
use app\model\Cart;
use app\model\Order;
use app\model\OrderQuotation;
use app\model\Member;
use app\model\Config;
use app\model\OrderStatus;
use app\model\OrderHistory;
use app\model\OrderGoods;
use app\model\Goods;
use app\model\Paymethod;
use app\model\Users;
use app\model\OrderStaff;
use app\model\Address;
use app\model\Category;
use app\model\TransportExtend;
use app\model\Message;
use app\model\Technical;
use app\model\Area;
use app\model\RegisterField;
use app\model\Store;
use app\model\Operatingcity;
use app\model\Incomelog;
use app\model\Geocoder;
use app\model\OrderImage;
use app\model\OrderAddress;

class OrderController extends Base
{

    public function list()
    {
        $uuid = $this->getuuid();
        $uid = UID();
        $uniacid = uniacid();
        $status = input('post.status');
        $admin = input('post.admin');
        $technical = input('post.technical');
        $publicorder = input('post.publicorder');
        $store = input('post.store');
        $ptype = input('post.ptype');
        $is_times = input('post.is_times');
        if (empty($ptype)) {
            $ptype = 1;
        }

        $query = Order::where(['uniacid' => $uniacid, 'ptype' => $ptype]);
        $query->with(['paymethod']);

        $Membermob = new Member;
        $Member = $Membermob->getUserByWechat();

        if ($admin == 1) {
        } elseif ($store == 1) {
            $data = Store::where(['uid' => UID()])->find();
            if ($data) {
                $data = $data->toArray();
                $query->where('sid', $data['id']);
            }
        } elseif ($technical == 1) {

            if (!empty($uuid) && !empty($uid)) {
                OrderStaff::where('uid', $uid)->update(['uuid' => $uuid]);
            }

            $withJoin = [
                'staff' => ['order_id', 'uuid', 'title', 'endTime', 'beginTime'],
            ];
            $query->withJoin($withJoin, 'left');
            $query->where(['staff.uuid' => $uuid]);
        } elseif ($publicorder == 1) {
            return $this->publicorder();
        } else {
            $query->where(['uid' => $Member['id']]);
        }

        if (!empty($is_times)) {
            $query->where('is_times', $is_times);
        }

        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $orderList = $query->order('id desc')->select()->toArray();

        //var_dump($query->getLastsql());

        $orderList = Order::setOrderList($orderList);

        $data["orderList"] = $orderList;
        //$data["amountLogistics"] = $amountLogistics;
        $data["isNeedLogistics"] = 1;
        $data['is_agent'] = $Member['is_agent'];

        return $this->json(['data' => $data]);
    }

    public function myorder()
    {
        $uniacid = uniacid();
        $status = input('post.status');
        $ptype = input('post.ptype');
        $is_times = input('post.is_times');
        if (empty($ptype)) {
            $ptype = 1;
        }
        $query = Order::where(['uniacid' => $uniacid]);
        if ($ptype == 3) {
            $query->where('ptype', 2);
            $query->where('is_user_send', 1);
            $query->where('price_type', 'in', '2,3');
        } else if ($ptype == 4) {
            $query->where('ptype', 2);
            $query->where('is_user_send', 1);
            $query->where('price_type', 1);
        } else if ($ptype == 2) {
            $query->where('ptype', 2);
            $query->where('is_user_send', 0);
        } else {
            $query->where('ptype', $ptype);
        }
        $query->with(['paymethod']);

        // $Membermob = new Member;
        // $Member = $Membermob->getUserByWechat();

        $Member = Member::where('id', UID())->find();
        $query->where(['uid' => $Member['id']]);


        if (!empty($is_times)) {
            $query->where('is_times', $is_times);
        }

        if (!empty($status)) {
            if ($status == 3) {
                $query->where('order_status_id', "in", '2,3');
            } else {
                $query->where('order_status_id', $status);
            }
        }

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();
        $res['data'] = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function technicalorderCount()
    {
        $uuid = $this->getuuid();
        $uid = UID();
        $uniacid = uniacid();
        $ptype = input('post.ptype');
        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['ptype' => $ptype]);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        if (!empty($uuid) && !empty($uid)) {
            OrderStaff::where('uid', $uid)->update(['uuid' => $uuid]);
        }
        $query->withJoin(['staff'], 'left');
        $query->where(['staff.uuid' => $uuid]);
        $res = $query->fetchSql(false)->field("COUNT(*) as count_id,order_status_id")->order('id desc')->group('order_status_id')->select();
        $data = [];
        foreach ($res as $item) {
            $data[$item['order_status_id']] = $item['count_id'];
        }
        return $this->json(['data' => $data]);
    }

    public function technicalorder()
    {
        $uuid = $this->getuuid();
        $uid = UID();
        $uniacid = uniacid();
        $status = input('post.status');
        $ptype = input('post.ptype');
        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['ptype' => $ptype]);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        if (!empty($uuid) && !empty($uid)) {
            OrderStaff::where('uid', $uid)->update(['uuid' => $uuid]);
        }
        $withJoin = [
            'staff' => ['order_id', 'uuid', 'title', 'endTime', 'beginTime'],
        ];
        $query->withJoin($withJoin, 'left');
        $query->where(['staff.uuid' => $uuid]);

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();

        $res['data'] = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function storeorder()
    {
        $uniacid = uniacid();
        $status = input('post.status');
        $ptype = input('post.ptype');

        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['uniacid' => $uniacid, 'ptype' => $ptype]);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $uuid = $this->getuuid();
        $Storedata = Store::where(['uuid' => $uuid])->find();
        if ($Storedata) {
            $Storedata = $Storedata->toArray();
            $query->where('sid', $Storedata['id']);
        }

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();


        $res['data'] = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function storeorderCount()
    {
        $uniacid = uniacid();
        $status = input('post.status');
        $ptype = input('post.ptype');

        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['uniacid' => $uniacid, 'ptype' => $ptype]);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $uuid = $this->getuuid();
        $Storedata = Store::where(['uuid' => $uuid])->find();
        if ($Storedata) {
            $Storedata = $Storedata->toArray();
            $query->where('sid', $Storedata['id']);
        }

        $res = $query->order('id desc')->field("COUNT(*) as count_id,order_status_id")->order('id desc')->group('order_status_id')->select();
        $data = [];
        foreach ($res as $item) {
            $data[$item['order_status_id']] = $item['count_id'];
        }
        return $this->json(['data' => $data]);
    }

    public function operatingcityorder()
    {
        $uniacid = uniacid();
        $status = input('post.status');
        $ptype = input('post.ptype');

        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['uniacid' => $uniacid, 'ptype' => $ptype]);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $uuid = $this->getuuid();

        $Operatingcitydata = Operatingcity::where(['uuid' => $uuid])->find();

        if ($Operatingcitydata) {
            $Operatingcitydata = $Operatingcitydata->toArray();

            if ($Operatingcitydata['areatype'] == 2) {
                $query->where('shipping_district_name', $Operatingcitydata['district_name']);
            } elseif ($Operatingcitydata['areatype'] == 1) {
                $query->where('shipping_city_name', $Operatingcitydata['city_name']);
            }
        }

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();


        $res['data'] = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function adminorder()
    {

        $uniacid = uniacid();
        $status = input('post.status');
        $ptype = input('post.ptype');

        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['uniacid' => $uniacid, 'ptype' => $ptype]);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();


        $res['data'] = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function teamorder()
    {

        $uniacid = uniacid();
        $status = input('post.status');
        $ptype = input('post.ptype');

        $Membermob = new Member;
        $Member = $Membermob->getUserByWechat();

        $where['uniacid'] = $uniacid;
        $where['uid'] = $Member['id'];

        $orderids = Incomelog::where($where)->column('order_id');

        $query = Order::where(['uniacid' => $uniacid]);

        if (!empty($ptype)) {
            $query->where('ptype', $ptype);
        }

        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $query->where('id', 'in', $orderids);
        //$uidlist = Member::getDepart($Member['id']);

        //$query->where(['uid' => $uidlist]);

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();


        $res['data'] = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function publicorder()
    {
        $identity = input('post.identity');

        $from['longitude'] = input('post.longitude');
        $from['latitude'] = input('post.latitude');

        $uniacid = uniacid();
        $ptype = input('post.ptype');
        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['uniacid' => $uniacid, 'ptype' => $ptype]);
        $uuid = $this->getuuid();
        if ($identity == 'technical') {

            $Technicaldata = Technical::where('uuid', $uuid)->find();
            if (!empty($Technicaldata)) {
                $cityName = $Technicaldata->city_name;
                $query->where(['sid' => (int)$Technicaldata->sid]);
                $orWhere = "`uniacid` = {$uniacid} and is_user_send = 1 and order_status_id = 1 and 
                 ptype = 2 and price_type = 1";
            }

            if (!empty($cityName)) {
                $query->where(['shipping_city_name' => $cityName]);
                $orWhere .= " and shipping_city_name = '{$cityName}'";
            } else {
                $query->where(['shipping_city_name' => '-1']);
                $orWhere .= " and shipping_city_name = -1";
            }

            $query->whereOr($orWhere);
        }

        $query->where(['order_status_id' => 2]);

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();
        $res['data'] = Order::setOrderList($res['data']);
        $uuid = $this->getuuid();
        foreach ($res['data'] as &$vo) {

            $vo['is_price'] = false;
            if ($identity == 'technical') {
                if ($vo['is_user_send'] == 1 && $vo['order_status_id'] == 1 && $vo['ptype'] == 2 && $vo['price_type'] == 1) {
                    $vo['statusStr'] = '待报价';
                    $vo['is_price'] = true;
                    $quotation = OrderQuotation::where([
                        'order_id' => $vo['id'],
                        'technical_id' => $uuid,
                    ])->find();
                    if ($quotation) {
                        $vo['statusStr'] = '已报价';
                    }
                }
            }

            if ($from['longitude'] && $from['latitude']) {

                $addressdata = OrderAddress::where(['order_id' => $vo['id'], 'ptype' => 1])->find();

                if (empty($addressdata)) {
                    $addressdata = Address::find($vo['address_id']);
                }

                if (!empty($addressdata)) {
                    $addressdata = $addressdata->toArray();
                    $to1['longitude'] = $addressdata['longitude'];
                    $to1['latitude'] = $addressdata['latitude'];
                    if ($vo['longitude'] && $vo['latitude']) {
                        $to1['longitude'] = $vo['longitude'];
                        $to1['latitude'] = $vo['latitude'];
                        $vo['realdistance'] = Geocoder::get_distance($from, $to1);
                    } else {
                        if ($to1['longitude'] && $to1['latitude']) {
                            $vo['realdistance'] = Geocoder::get_distance($from, $to1);
                        }
                    }
                }

                if ($vo['is_errands'] == 1) {
                    $takeaddressdata = OrderAddress::where(['order_id' => $vo['id'], 'ptype' => 2])->find();

                    if (empty($takeaddressdata)) {
                        $takeaddressdata = Address::find($vo['take_address_id']);
                    }

                    if (!empty($takeaddressdata)) {
                        $takeaddressdata = $takeaddressdata->toArray();
                        $to2['longitude'] = $takeaddressdata['longitude'];
                        $to2['latitude'] = $takeaddressdata['latitude'];
                        if ($to2['longitude'] && $to2['latitude']) {
                            $vo['takerealdistance'] = Geocoder::get_distance($from, $to2);
                        }
                    }
                }
            }
        }

        $data['data'] = $res;

        //兼容旧版
        $data['data']["orderList"] = $res['data'];

        return $this->json($data);
    }

    public function quotation()
    {
        $order_id = input('post.order_id');
        $price = input('post.price');
        $uuid = $this->getuuid();
        $msg = '报价';
        $quotation = OrderQuotation::where([
            'order_id' => $order_id,
            'technical_id' => $uuid,
        ])->find();
        if (!$quotation) {
            $order_history['order_id'] = $order_id;
            $order_history['remark'] = $msg;
            $order_history['create_time'] = time();
            $order_history['notify'] = 1;
            OrderHistory::create($order_history);

            $data['order_id'] = $order_id;
            $data['technical_id'] = $uuid;
            $data['price'] = $price;
            $data['create_time'] = time();
            $data['status'] = 0;
            if (OrderQuotation::create($data)) {
                return $this->json(['msg' => '提交成功']);
            }
            return $this->json(['msg' => '提交失败']);
        } else {
            return $this->json(['msg' => '重复提交']);
        }
    }

    public function detail()
    {
        $identity = input('get.identity');
        $id = input('get.id');
        $data = Order::order_info($id);

        if (!empty($data['orderInfo']['cat_id'])) {
            $data['orderInfo']['cateMap']['image'] = Category::getImage($data['orderInfo']['cat_id']);
        } else {
            foreach ($data['goods'] as &$vo) {
                $vo['goods']['image'] = toimg($vo['goods']['image']);
            }
        }
        if ($data['orderInfo']['additional'] > 0 && $data['orderInfo']['additional_pay_time'] == 0) {
            $tmplIds = Config::getconfig('subscribemessage');
            $data['tmplIds'][] = $tmplIds['complete_tpl'];
        }
        $data['orderInfo']['orderStatus']['quotation_price'] = '';
        $data['orderInfo']['orderStatus']['is_quotation_price'] = false;
        $data['orderInfo']['orderStatus']['is_price'] = false;
        if ($identity == 'technical') {
            if ($data['orderInfo']['is_user_send'] == 1 && $data['orderInfo']['order_status_id'] == 1 && $data['orderInfo']['ptype'] == 2 && $data['orderInfo']['price_type'] == 1) {
                $data['orderInfo']['orderStatus']['name_yuyue'] = '待报价';
                $data['orderInfo']['orderStatus']['is_price'] = true;
                $uuid = $this->getuuid();
                $quotation = OrderQuotation::where([
                    'order_id' => $id,
                    'technical_id' => $uuid,
                ])->find();
                if ($quotation) {
                    $data['orderInfo']['orderStatus']['name_yuyue'] = '已报价';
                    $data['orderInfo']['orderStatus']['quotation_price'] = $quotation['price'];
                    $data['orderInfo']['orderStatus']['is_quotation_price'] = true;
                }
            }
        } else {
            if ($data['orderInfo']['is_user_send'] == 1 && $data['orderInfo']['order_status_id'] == 1 && $data['orderInfo']['ptype'] == 2 && $data['orderInfo']['price_type'] == 1) {
                if ($data['orderInfo']['is_select_quotation'] == 0) {
                    $data['orderInfo']['orderStatus']['name_yuyue'] = '待选择师傅';
                } else {
                    $data['orderInfo']['orderStatus']['name_yuyue'] = '已选师傅，等待支付';
                }
            }
        }


        $addressdata = OrderAddress::where(['order_id' => $id, 'ptype' => 1])->find();
        if (empty($addressdata)) {
            $addressdata = Address::find($data['orderInfo']['address_id']);
        }
        if (!empty($addressdata)) {
            $addressdata = $addressdata->toArray();
            $data['orderInfo']['address'] = $addressdata;
        }

        if ($data['orderInfo']['is_errands'] == 1) {

            $takeaddressdata = OrderAddress::where(['order_id' => $id, 'ptype' => 2])->find();

            if (empty($takeaddressdata)) {
                $takeaddressdata = Address::find($data['orderInfo']['take_address_id']);
            }

            if (!empty($takeaddressdata)) {
                $takeaddressdata = $takeaddressdata->toArray();

                $data['orderInfo']['take_address'] = $takeaddressdata;
            }
        }
        return $this->json(['data' => $data]);
    }

    public function errandscreate()
    {
        $ordermod = new Order;
        $payment = input('post.paymentType');
        $address_id = input('post.address_id');
        $take_address_id = input('post.take_address_id');
        $remark = input('post.remark');
        $distance = input('post.distance');
        $amountTotle = input('post.amountTotle');

        $order['distance'] = $distance;
        $order['total'] = $amountTotle;
        $order['number'] = 1;

        //支付方式
        if (!empty($payment)) {
            $order['payment_code'] = $payment;

            $paymentdata = Paymethod::where(['code' => $payment, 'uniacid' => uniacid()])->find();

            $order['pay_method_id'] = $paymentdata->id;
        }

        $order['address_id'] = $address_id;
        $order['take_address_id'] = $take_address_id;
        $order['remark'] = $remark;
        $order['uid'] = UID();

        $ordermod = new Order;
        $data = $ordermod->add_order($order);

        return $this->json(['data' => $data]);
    }

    public function createBout()
    {
        $order = input('post.');

        $order_id = $order['order_id'];
//        $skuId = $order['sku_id'];
        $servicetime = $order['service_time'];
        $addressId = $order['address_id'];

        $boutOrderInfo = Boutcardorder::find($order_id);
        $boutOrderStatus = 2;
        if (!empty($boutOrderInfo)) {
            $boutOrderInfo = $boutOrderInfo->toArray();

            if ($boutOrderInfo['available_times'] - $boutOrderInfo['used_times'] - $boutOrderInfo['occupy_times'] < 1) {

                Boutcardorder::update(['id' => $order_id, 'status' => '3']);

                return $this->json(['errno' => 0, 'msg' => '次卡无可使用次数', 'data' => 0]);
            }
            if ($boutOrderInfo['available_times'] - $boutOrderInfo['used_times'] - $boutOrderInfo['occupy_times'] == 1) {
                $boutOrderStatus = 3;
            }


            $goods = Goods::find($boutOrderInfo['goods_id']);
            if (!empty($goods)) {
                $goods = $goods->toArray();
            } else {
                $goods = [];
            }

//            $skuInfo = GoodsSkuValue::find($skuId);
//            if(!empty($skuInfo)){
//                $skuInfo = $skuInfo->toArray();
//            }else{
//                $skuInfo = [];
//            }
        } else {
            return $this->json(['errno' => 0, 'msg' => '次卡不存在', 'data' => 0]);
        }

        $price = round($boutOrderInfo['price'] / $boutOrderInfo['available_times'], 2);

        $data['uniacid'] = uniacid();
        $data['ptype'] = 2;
        $data['boud_order_id'] = $order_id;
        $data['is_bout_order'] = 1;
        $data['order_num_alias'] = build_order_no();

        $servicetime = explode(' ', $servicetime);
        $timetmp = explode('-', $servicetime[1]);
        $data['beginTime'] = strtotime($servicetime[0] . ' ' . $timetmp[0]);
        $data['endTime'] = strtotime($servicetime[0] . ' ' . $timetmp[1]);

        //付款人
        $Membermob = new Member;
        $payMember = $Membermob->getUserByWechat();

        $data['uid'] = $payMember['id'];
        $data['name'] = $payMember['username'];
        $data['email'] = $payMember['email'];
        $data['tel'] = $payMember['telephone'];

        $shipping = Address::find($addressId);
        if (!empty($shipping)) {
            $shipping = $shipping->toArray();

            $shipping_city_id = empty($shipping['city_id']) ? '' : $shipping['city_id'];
            $data['shipping_name'] = empty($shipping['name']) ? '' : $shipping['name'];
            $data['shipping_tel'] = empty($shipping['telephone']) ? '' : $shipping['telephone'];

            $data['shipping_province_name'] = empty($shipping['province_name']) ? '' : $shipping['province_name'];
            $data['shipping_city_name'] = empty($shipping['city_name']) ? '' : $shipping['city_name'];
            $data['shipping_district_name'] = empty($shipping['district_name']) ? '' : $shipping['district_name'];

            $data['shipping_province_id'] = empty($shipping['province_id']) ? '' : $shipping['province_id'];
            $data['shipping_city_id'] = empty($shipping['city_id']) ? '' : $shipping['city_id'];
            $data['shipping_district_id'] = empty($shipping['district_id']) ? '' : $shipping['district_id'];
            $address_name = '';
            if (!empty($shipping['address'])) {
                $address_name .= $shipping['region_name'];
            }
            if (!empty($shipping['address'])) {
                $address_name .= $shipping['address'];
            }
            $data['shipping_address'] = $address_name;
        }


        $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
        $data['create_time'] = time();
        $data['update_time'] = time();

        $coder = Geocoder::geocoding($data['shipping_province_name'] . $data['shipping_city_name'] . $data['shipping_district_name'] . $data['shipping_address']);
        $data['latitude'] = $coder['latitude'];
        $data['longitude'] = $coder['longitude'];
        $data['total'] = $price;

        $data['order_status_id'] = 2;
        $data['deliverymode'] = 1;

        $Orderdata = Order::create($data);
        $orderId = $Orderdata->id;

        OrderGoods::create([
            'order_id' => $orderId,
            'goods_id' => $goods['id'],
            'name' => $goods['name'],
            'model' => $goods['model'],
            'image' => $goods['image'],
            'sku' => '',
            'price' => $price,
            'total' => $price,
            'quantity' => 1
        ]);
        if ($addressId) {
            $Address = Address::find($addressId);
            if ($Address) {
                $Address = $Address->toArray();
                unset($Address['id']);
                $Address['order_id'] = $orderId;
                $Address['ptype'] = 1;
                OrderAddress::create($Address);
            }
        }

        Boutcardorder::where('id', $order_id)
            ->inc('occupy_times', 1)
            ->update(['status' => $boutOrderStatus]);

        return $this->json(['errno' => 0, 'data' => 1]);
    }

    public function create()
    {
        $ordermod = new Order;
        $payment = input('post.paymentType');
        $price_type = input("post.price_type", 0);

//        dump($price_type);die;
        $cartid = input('post.cartid');
        $cartid = input('post.cartid');
        $video_src = input('post.videoSrc', '');
        $tuanid = input('post.tuanid');
        $jointuanid = input('post.jointuanid');
        $technicalId = input('post.technicalId');
        if ($technicalId == 'undefined') {
            $technicalId = '';
        }
        $sid = input('post.sid/d');
        $address_id = input('post.address_id');
        $remark = input('post.remark');
        $shipping = input('post.shipping');
        $couponId = input('post.couponId');
        $goods_id = input('post.goodsId');
        $cat_id = input('post.cat_id');
        $total = input('post.total');
        // 一口价
        if ($price_type == 2 && !empty($cat_id)) {
            //用户发布需求订单
            $cat = Category::find($cat_id);
            if (!empty($cat) && $cat['price'] > 0) {
                $total = $cat['price'];
            } else {
                throw new ValidateException('价格错误');
            }
        }
        $sku = input('post.sku');
        $is_PayPoints = input('post.is_PayPoints');
        $number = input('post.number');
        $orderimage = input('post.orderimage');
        $is_skumore = input('post.is_skumore');
        $skumore = json_decode(input('post.skumore'), true);
        $combination_ids = input('post.combination_ids');
        $servicetime = input('post.servicetime');
        $is_times = input('post.is_times');
        $servicetime = explode(' ', $servicetime);
        $timetmp = explode('-', $servicetime[1]);

        $order['beginTime'] = strtotime($servicetime[0] . ' ' . $timetmp[0]);
        $order['endTime'] = strtotime($servicetime[0] . ' ' . $timetmp[1]);
        $order['is_times'] = $is_times;

        $order['combination_ids'] = $combination_ids;
        $order['cartid'] = $cartid;
        $order['sid'] = $sid;
        $order['couponId'] = $couponId;
        $order['goods_id'] = $goods_id;
        $order['cat_id'] = $cat_id;
        $order['total'] = $total;
        $order['msid'] = $msid;
        $order['tuanid'] = $tuanid;
        $order['jointuanid'] = $jointuanid;
        $order['video_src'] = $video_src;
        $order['sku'] = $sku;
        $order['cat_id'] = $cat_id;
        $order['is_skumore'] = $is_skumore;
        $order['skumore'] = $skumore;
        $order['number'] = $number;
        //需要配送的
        if (!empty($shipping)) {
            $order['shipping_method'] = '快递';
        } else {
            $order['shipping_method'] = '';
        }

        //支付方式
        if (!empty($payment)) {
            $order['payment_code'] = $payment;

            $paymentdata = Paymethod::where(['code' => $payment, 'uniacid' => uniacid()])->find();

            $order['pay_method_id'] = $paymentdata->id;
        }

        $order['address_id'] = $address_id;
        $order['technicalId'] = $technicalId;

        $order['remark'] = $remark;
        $order['is_PayPoints'] = $is_PayPoints;
        $order['uid'] = UID();
        $order['price_type'] = $price_type;
        //var_dump($order);

        $data = $ordermod->add_order($order);
        //图片
        if ($data['id']) {
            OrderImage::where('order_id', $data['id'])->delete();
            if (!empty($orderimage)) {
                foreach (explode(',', $orderimage) as $image) {
                    OrderImage::create([
                        'order_id' => (int)$data['id'],
                        'uniacid' => uniacid(),
                        'image' => $image
                    ]);
                }
            }

            if (!empty($technicalId)) {
                $order_staff['order_id'] = $data['id'];
                $order_staff['uuid'] = $technicalId;
                $order_staff['create_time'] = time();
                OrderStaff::addstaff($order_staff);
                Message::sendMiniStaff($order);
                Message::distribution($technicalId, $data);
            }
        }

        return $this->json(['data' => $data]);
    }

    public function yuyuetime()
    {
        $id = input('post.id');
        $timestype = input('post.timestype');
        $timesdate = input('post.timesdate');
        $servicetime = input('post.servicetime');

        $servicetime = explode(' ', $servicetime);
        $timetmp = explode('-', $servicetime[1]);

        $order['beginTime'] = strtotime($servicetime[0] . ' ' . $timetmp[0]);
        $order['endTime'] = strtotime($servicetime[0] . ' ' . $timetmp[1]);

        $order['timestype'] = $timestype;
        $order['timesdate'] = $timesdate;
        $order['id'] = $id;

        Order::update($order);
        return $this->json(['data' => $data]);
    }

    public function close()
    {
        $this->cancel();
    }

    public function cancel()
    {
        $orderid = input('post.orderid');

        Order::cancel_order($orderid);

        $data['orderid'] = $orderid;

        return $this->json(['data' => $data]);
    }

    public function receiving()
    {
        $orderid = input('post.orderid');

        Order::receiving($orderid);

        $data['orderid'] = $orderid;

        return $this->json(['data' => $data]);
    }

    public function additional()
    {
        $orderid = input('post.orderid');
        $additional = input('post.additional');

        $order['additional'] = $additional;
        Order::where('id', $orderid)->update($order);

        $order_info = Order::find($orderid);
        if (!empty($order_info)) {
            $order_info = $order_info->toArray();
        }
        Message::sendMiniItional($order_info);
        return $this->json(['data' => $data]);
    }


    public function complete()
    {
        $orderid = input('post.orderid');
        try {
            $data = Order::complete($orderid);
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }

        return $this->json(['data' => $data]);
    }

    function staff()
    {
        $id = input('post.id');
        $uuid = input('post.uuid');
        $msg = '派单';
        if (empty($uuid)) {
            $uuid = $this->getuuid();
            $msg = '接单';
        }

        $technical = Technical::where(['uuid' => $uuid])->find();
        if (!empty($technical)) {
            $bailConfig = Config::getconfig('bail');

            if ($bailConfig['is_technical_bail'] == 1) {
                if ($technical->bail < $bailConfig['is_technical_bail_min_amount']) {
                    return $this->json(['msg' => '保证金低于限额，无法接单', 'errno' => 1]);
                }
            }
        }

        $orderInfo = Order::find($id);

        if (!empty($orderInfo)) {
            $orderInfo = $orderInfo->toArray();

            if ($orderInfo['order_status_id'] == 2) {
                $order_history['order_status_id'] = 3;
                $orderup['order_status_id'] = 3;
            }

            try {

                $order_history['order_id'] = $orderInfo['id'];
                $order_history['remark'] = $msg;
                $order_history['create_time'] = time();
                $order_history['notify'] = 1;

                OrderHistory::create($order_history);

                if ($uuid) {
                    $order_staff['order_id'] = $orderInfo['id'];
                    $order_staff['uuid'] = $uuid;
                    $order_staff['create_time'] = time();
                    OrderStaff::addstaff($order_staff);
                    Message::sendMiniStaff($orderInfo);
                }
                $orderup['id'] = $orderInfo['id'];
                order::update($orderup);
            } catch (\Exception $e) {
                throw new ValidateException($e->getMessage());
            }
        }

        return $this->json(['msg' => $msg . '成功']);
    }

    //付款凭证上传
    public function offlinepayment()
    {
        $orderid = input('post.orderid');
        $img = input('post.image');
        $remark = input('post.remark');
        $order_info = Order::order_info($orderid);
        $order = new Order;
        $insert = $order->OfflinepaymentTap($orderid, $img, $remark);

        if ($insert) {
            Order::offline_order($orderid);

            $errno = 0;
            $message = '提交成功，请等待管理员审核！';
            $data = [
                'ptype' => $order_info['orderInfo']['ptype'],
                'price_type' => $order_info['orderInfo']['price_type'],
            ];
            return $this->json(['message' => $message, 'data' => $data]);
        } else {
            $errno = 1;
            $message = '提交失败，请重新尝试!';
            return $this->json(['message' => $message, 'data' => $data]);
        }
    }

    public function custom()
    {
        $id = input('post.id');
        $registerfield = json_decode(input('post.registerfield'), true);

        $data = RegisterField::fieldToData($registerfield);

        Order::where('id', $id)->update(['customtext' => $data['customtext']]);

        $msg = '提交成功';
        return $this->json(['msg' => $msg, 'data' => $data]);
    }

    public function taketotal()
    {
        $address_id = input('post.address_id');
        $take_address_id = input('post.take_address_id');

        $addressdata = Address::find($address_id);
        if (!empty($addressdata)) {
            $addressdata = $addressdata->toArray();
        }
        $takeaddressdata = Address::find($take_address_id);
        if (!empty($takeaddressdata)) {
            $takeaddressdata = $takeaddressdata->toArray();
        }

        if ($addressdata['longitude'] && $addressdata['latitude'] && $takeaddressdata['longitude'] && $takeaddressdata['latitude']) {
            $from['longitude'] = $addressdata['longitude'];
            $from['latitude'] = $addressdata['latitude'];
            $to['longitude'] = $takeaddressdata['longitude'];
            $to['latitude'] = $takeaddressdata['latitude'];

            $data["distance"] = Geocoder::get_distance($from, $to);
        }

        if ($data["distance"]) {
            $errands = Config::getconfig('errands');

            $data["amountTotle"] = round(($data["distance"] * $errands['mileageprice']), 2);
        }

        return $this->json(['data' => $data]);
    }

    public function total()
    {
        $charge = 0;
        $cartid = input('post.cartid');
        $msid = input('post.msid');
        $tuanid = input('post.tuanid');
        $ptype = input('post.ptype');
        $address_id = input('post.address_id');
        $peisongType = input('post.peisongType');
        $technicalId = input('post.technicalId');
        $serviceTime = input('post.serviceTime');
        if ($technicalId == 'undefined') {
            $technicalId = '';
        }

        if (empty($cartid)) {
            $goods_id = input('post.goodsId');
            $sku = input('post.sku');
            $number = input('post.number');
            $is_skumore = input('post.is_skumore');
            $skumore = json_decode(input('post.skumore'), true);
            $Goods = new Goods;
            $buygoods = $Goods->cartGoods([
                'id' => $goods_id,
                'msid' => $msid,
                'tuanid' => $tuanid,
                'sku' => $sku,
                'quantity' => $number,
                'is_skumore' => $is_skumore,
                'skumore' => $skumore,
                'serviceTime' => $serviceTime
            ]);
            $data["price"] = $buygoods['price'];
            $data["amountTotle"] = $buygoods['total'];
            $data["totalPayPoints"] = $buygoods['totalPayPoints'];
            $data['totalPointsPrice'] = $buygoods['totalPointsPrice'];
            $data['is_additional'] = $buygoods['is_additional'];
            $data['special_time_txt'] = $buygoods['special_time_txt'];

            if (empty($buygoods['weight'])) {
                $buygoods['weight'] = 0.1;
            }
            $weight = $buygoods['weight'];
            //var_dump($weight);
        } else {
            $cart = new Cart;
            $cartgoods = $cart->getlistbyid($cartid);
            $data["amountTotle"] = $cartgoods['totalprice'];
            $data["totalPayPoints"] = $cartgoods['totalPayPoints'];
            $data['totalPointsPrice'] = $cartgoods['totalPointsPrice'];
            $data['is_additional'] = $cartgoods['is_additional'];
            $weight = $cartgoods['weight'];
        }

        $data["thefare"] = 0;

        //收货人
        if (!empty($address_id)) {
            $shipping = Address::find($address_id);
            if (!empty($shipping)) {
                $shipping = $shipping->toArray();
            }
            if ($ptype == 1) {

                $shipping_city_id = empty($shipping['city_id']) ? '' : $shipping['city_id'];

                $Transport = (new TransportExtend)->calc_transport($weight, $shipping_city_id);
                $amountLogistics = $Transport['price'];
            }

            if ($technicalId && $ptype == 2) {
                $thefare = Address::getthefare($address_id, $technicalId);
                $data["distance"] = $thefare['distance'];
                $data["thefare"] = $thefare['thefare'];
            }
        }

        $Membermob = new Member;
        $Member = $Membermob->getUserByWechat();

        //订阅消息模板
        $tmplIds = Config::getconfig('subscribemessage');
        $data['tmplIds'][] = $tmplIds['pay_tpl'];
        $data['tmplIds'][] = $tmplIds['staff_tpl'];
        if ($data['is_additional'] == 1) {
            $data['tmplIds'][] = $tmplIds['itional_tpl'];
        } else {
            $data['tmplIds'][] = $tmplIds['complete_tpl'];
        }

        $data["memberPoints"] = $Member['points'];
        $test['shipping_method'] = '快递';
        $test['weight'] = $weight;
        $test['shipping_city_id'] = $shipping_city_id;
        $data["amountLogistics"] = (float)$amountLogistics;
        $data['charge'] = $charge;
        $data["isNeedLogistics"] = 1;
        $data["peisongType"] = $peisongType;
        $data['test'] = $test;
        $data["amountTotle"] = round($data["amountTotle"], 2);


        return $this->json(['data' => $data]);
    }

    //直接使用余额支付
    public function pay()
    {
        $uid = UID();
        $payPwd = input('post.payPwd');
        if (empty($payPwd)) {
            return $this->json(['errno' => 1, 'message' => '请输入支付密码']);
        }

        $memberinfo = Member::find($uid);
        if (empty($memberinfo)) {
            return $this->json(['errno' => 1, 'message' => '用户不存在']);
        }

        if ($memberinfo->pay_pwd != $payPwd) {
            return $this->json(['errno' => 1, 'message' => '支付密码错误']);
        }


        $orderid = input('post.orderid');

        //付款前检查库存
        $result = Order::getGoodsquantitiy($orderid);

        if ($result) {
            $orderinfo = Order::find($orderid);

            if (!empty($orderinfo)) {
                $orderinfo = $orderinfo->toArray();
                if ($orderinfo['is_user_send'] == 1 &&
                    $orderinfo['order_status_id'] == 1 &&
                    $orderinfo['ptype'] == 2 &&
                    $orderinfo['price_type'] == 1 &&
                    $orderinfo['is_select_quotation'] == 0
                ) {
                    return $this->json(['errno' => 1, 'msg' => '请先选择师傅']);
                }

                $money = $orderinfo['total'];
                $Member = Member::find(UID());
                if (!empty($Member) && ($Member->balance >= $money)) {
                    Member::where('id', UID())
                        ->dec('balance', $money)
                        ->update();

                    Order::update(['id' => $orderid, 'pay_time' => time(), 'payment_code' => 'balance_pay']);

                    $ordermod = new Order;
                    $ordermod->pay_order(['id' => $orderid]);

                } else {
                    $errno = 1;
                    $message = '余额不足';
                }
            } else {
                $errno = 1;
                $message = '订单不存在';
            }
        } else {
            $errno = 2;
            $message = '库存量不足';
        }

        return $this->json(['msg' => $message, 'message' => $message, 'errno' => $errno, 'data' => $data]);
    }

    public function delivery()
    {

        $orderid = input('post.orderid');

        $orderinfo = Order::find($orderid);
        if (!empty($orderinfo)) {
            $orderinfo = $orderinfo->toArray();
            $order_history['order_id'] = $orderid;
            $order_history['order_status_id'] = 5;
            $order_history['remark'] = "确认完成";
            $order_history['create_time'] = time();
            $order_history['notify'] = 1;
            OrderHistory::create($order_history);

            $order['order_status_id'] = 5;
            Order::where('id', $orderid)->update($order);
        } else {
            $errno = 1;
            $message = '订单不存在';
        }
        return $this->json(['message' => $message, 'errno' => $errno, 'data' => $data]);
    }

    //支付方式列表
    public function paymethod()
    {

        $data = Paymethod::where(['uniacid' => uniacid(), 'status' => 1])
            ->order('sort asc')
            ->select()
            ->toArray();
        $data[0]['default'] = $data[0]['default']['code'];
        foreach ($data as $i => $vo) {
            if (empty($vo['code'])) {
                unset($data[$i]);
            }
            if (($vo['code'] == 'wx_pay')) {
                $data[0]['default'] = $vo['code'];
            }
        }
        if (empty($data)) {
            Paymethod::update(['code' => 'wx_pay', 'uniacid' => 0]);
            $data = Paymethod::where(['uniacid' => 0])->order('sort asc')->select()->toArray();
        }
        if (empty($data[0]['default'])) {
            $data[0]['default'] = $data[0]['code'];
        }
        return $this->json(['data' => $data]);
    }

    public function getSelectList()
    {
        $order_id = input('order_id');
        $query = OrderQuotation::where(['order_id' => $order_id]);
        $data = $query->with(['technical'])->order('status desc,id desc')->select()->toArray();
        return $this->json(['data' => $data]);
    }

    public function doSelectList()
    {
        $order_id = input('order_id');
        $quotation_id = input('quotation_id');
        $orderInfo = Order::find($order_id);
        if (!empty($orderInfo)) {
            $quotation = OrderQuotation::where([
                'order_id' => $order_id,
                'id' => $quotation_id,
            ])->find();
            if (!$quotation) {
                return $this->json(['msg' => '操作失败']);
            }
            $quotation = $quotation->toArray();
            $orderInfo = $orderInfo->toArray();
            if ($orderInfo['order_status_id'] == 1) {
//                $orderup['order_status_id'] = 3;
                $orderup['total'] = $quotation['price'];
                $orderup['is_select_quotation'] = $quotation_id;
            }
            Order::update($orderup, [
                'id' => $order_id,
            ]);
            OrderQuotation::update(['status' => -1], ['order_id' => $order_id]);
            OrderQuotation::update(['status' => 1], ['order_id' => $order_id, 'id' => $quotation_id]);
            return $this->json(['msg' => '操作成功']);
        }
        return $this->json(['msg' => '操作失败']);
    }

    public function visit_fee()
    {
        return $this->json(['msg' => 'ok', "data" => Config::getconfig()['visit_fee']]);
    }


    //代客下单
    function replace()
    {
        $msg = '下单成功';
        $postdata = input('post.');

        $order['goods_id'] = $postdata['goods_id'];
        $order['uid'] = $postdata['uid'];
        $order['sku'] = $postdata['sku'];

        $type = $postdata['type'];
        if ($type == 'store') {
            $uuid = $this->getuuid();
            $store = Store::where(['uuid' => $uuid])->find();
            if (empty($store)) {
                return $this->json(['msg' => '下单失败', 'errno' => 1]);
            }
            $order['sid'] = $store->id;
        } else {
            $order['tid'] = UID();
        }

        $data = (new Order)->replaceOrder($order);

        return $this->json(['msg' => $msg, 'data' => $data]);
    }
}
